#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <vector>
#include <string>

static void die(const char *msg) {
    int err = errno;
    fprintf(stderr, "[%d] %s\n", err, msg);
    abort();
}

static uint32_t read_le32(const uint8_t *buf) {
    uint32_t val = 0;
    memcpy(&val, buf, 4);
    return val;
}

static void write_le32(uint8_t *buf, uint32_t val) {
    memcpy(buf, &val, 4);
}

static int32_t send_req(int fd, const std::vector<std::string> &cmd) {
    uint32_t len = 4;  // 参数数量字段
    for (const std::string &s : cmd) {
        len += 4 + s.size();  // 每个参数的长度字段 + 内容
    }
    if (len > 4096) {
        return -1;
    }

    char wbuf[4 + 4096];
    write_le32((uint8_t *)&wbuf[0], len);  // 消息长度（包括参数数量字段）
    write_le32((uint8_t *)&wbuf[4], cmd.size());  // 参数数量
    size_t cur = 8;
    for (const std::string &s : cmd) {
        write_le32((uint8_t *)&wbuf[cur], s.size());  // 参数长度
        memcpy(&wbuf[cur + 4], s.data(), s.size());   // 参数内容
        cur += 4 + s.size();
    }

    uint32_t total_len = len + 4;  // 包括长度字段本身
    printf("Sending %u bytes: ", total_len);
    for (uint32_t i = 0; i < total_len; i++) {
        printf("%02x ", (uint8_t)wbuf[i]);
        if (i % 16 == 15) printf("\n");
    }
    printf("\n");
    
    // 打印字符串内容用于调试
    printf("Command details:\n");
    printf("  Message length: %u\n", len);
    printf("  Number of args: %u\n", (uint32_t)cmd.size());
    for (size_t i = 0; i < cmd.size(); i++) {
        printf("  Arg %zu: '%s' (len=%zu)\n", i, cmd[i].c_str(), cmd[i].size());
    }

    return write(fd, wbuf, total_len) == (ssize_t)total_len ? 0 : -1;
}

static int32_t read_res(int fd) {
    char rbuf[4 + 4096 + 1];
    errno = 0;
    int32_t err = read(fd, rbuf, 4);
    if (err != 4) {
        if (err < 0) {
            perror("read");
        } else {
            fprintf(stderr, "EOF\n");
        }
        return -1;
    }

    uint32_t len = read_le32((uint8_t *)rbuf);
    if (len > 4096) {
        fprintf(stderr, "too long\n");
        return -1;
    }

    err = read(fd, &rbuf[4], len);
    if (err != (int32_t)len) {
        if (err < 0) {
            perror("read");
        } else {
            fprintf(stderr, "EOF\n");
        }
        return -1;
    }

    rbuf[4 + len] = '\0';
    printf("server says: [%u] %s\n", len, &rbuf[4]);
    return 0;
}

int main() {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        die("socket()");
    }

    struct sockaddr_in addr = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(1234);
    addr.sin_addr.s_addr = ntohl(INADDR_LOOPBACK);
    int rv = connect(fd, (const struct sockaddr *)&addr, sizeof(addr));
    if (rv) {
        die("connect");
    }

    // 发送一个简单的命令
    std::vector<std::string> cmd = {"keys"};
    int32_t err = send_req(fd, cmd);
    if (err) {
        printf("send failed\n");
        close(fd);
        return 1;
    }
    
    err = read_res(fd);
    if (err) {
        printf("read failed\n");
    }

    close(fd);
    return 0;
} 